<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

$orgMap = [];

class Project extends Model
{
    protected  $table='project';

    protected $fillable = [
        'team_id',
        'org_id',
        'name',
        'service_target',
        'project_type',
        'volunteer_security',
        'list_photo',
        'photo',
        'province_id',
        'province_name',
        'city_id',
        'city_name',
        'county_id',
        'county_name',
        'addr',
        'content',
        'contact_name',
        'contact_phone',
        'contact_phone_public',
        'work_tel',
        'work_tel_public',
        'work_email',
        'join_end',
        'begin',
        'end',
        'lng',
        'lat',
        'verify_status',
        'verify_msg',
        'status',
        'identifier',
        'people_count',
        'join_people_count',
        'reward_time',
        'browse_times',
        'region',
        'address',
        'custom_payment_config',
        'custom_config',
    ];

    protected $casts = [
        'photo' => 'array',
        'custom_payment_config' => 'array',
        'custom_config' => 'array'
    ];

    public function getCustomPaymentConfigAttribute() {
        if (isset($this->attributes['custom_payment_config'])) {
            try {
                $this->attributes['custom_payment_config'] = json_decode($this->attributes['custom_payment_config']);
            }catch (\Exception $e) {

            }
//            dd($this->attributes['extends']);
            return $this->attributes['custom_payment_config'];
        }

        return null;
    }

    public function setCustomPaymentConfigAttribute($value) {
        if (!empty($value)) {
            $value = json_encode($value);
        }

        $this->attributes['custom_payment_config'] = $value;
    }

    public function getCustomConfigAttribute() {
        if (isset($this->attributes['custom_config'])) {
            try {
                $this->attributes['custom_config'] = json_decode($this->attributes['custom_config']);
            }catch (\Exception $e) {

            }
//            dd($this->attributes['extends']);
            return $this->attributes['custom_config'];
        }

        return null;
    }

    public function setCustomConfigAttribute($value) {
        if (!empty($value)) {
            $value = json_encode($value);
        }

        $this->attributes['custom_config'] = $value;
    }

    public function getPhotoAttribute() {
        if (isset($this->attributes['photo'])) {
            try {
                $this->attributes['photo'] = json_decode($this->attributes['photo']);
            }catch (\Exception $e) {

            }

            if (is_array($this->attributes['photo'])) {
                return join(',', $this->attributes['photo']);
            }

            return $this->attributes['photo'];
        }

        return null;
    }

    public function setPhotoAttribute($value) {
        if (!empty($value)) {
            $value = explode(',', $value);
            $value = json_encode($value);
        }

        $this->attributes['photo'] = $value;
    }

    protected $appends = array('progress', 'address', 'region', 'preview_url');

    // '1'=>'未开始', '2'=>'招募中', '3'=>'已满员', '4'=>'进行中', '5'=>'已结束'
    public function getProgressAttribute()
    {
        if ($this->status == 0) {
            return 255;
        }

        if(time() > $this->end)
        {
            return 5;
        }elseif(time() > $this->begin) {
            return 4;
        }else{
            return $this->join_people_count >= $this->people_count ? 3 : 2;
        }
        /*if(time() < strtotime($this->join_begin))
        {
            return 1;
        }else*/
        //if(strtotime(date('Y-m-d')) <= $this->join_end)
        //{
        //    return $this->join_people_count >= $this->people_count ? 3 : 2;
        //}elseif(time() < strtotime($this->begin))
        //{
        //    return 2;
        //}elseif(time() < strtotime($this->end))
        //{
        //    return 4;
        //}else
        //{
        //    return 5;
        //}

    }

    public function getPreviewUrlAttribute() {
        if (!$this->org_id) {
            return null;
        }

        $org = null;

        if (isset($orgMap[$this->org_id])) {
            $org = $orgMap[$this->org_id];
        } else {
            $orgMap[$this->org_id] = $org = Org::findOrFail($this->org_id);
        }

        return $org->wechat_app_url.'/project/detail/'. $this->id .'?preview=1';
    }

    public function getBeginAttribute() {
        if (isset($this->attributes['begin'])) {
            $date = new Carbon($this->attributes['begin']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setBeginAttribute($value) {
        $value = strtotime(date('Y-m-d', $value).' 00:00:00');

        $date = new Carbon();
        $date->setTimestamp($value);

        $this->attributes['begin'] = $date->toDateTimeString();
    }

    public function getEndAttribute() {
        if (isset($this->attributes['end'])) {
            $date = new Carbon($this->attributes['end']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setEndAttribute($value) {
        $value = strtotime(date('Y-m-d', $value).' 23:59:59');

        $date = new Carbon();
        $date->setTimestamp($value);
        $this->attributes['end'] = $date->toDateTimeString();
    }

    public function getJoinBeginAttribute() {
        if (isset($this->attributes['join_begin'])) {
            $date = new Carbon($this->attributes['join_begin']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setJoinBeginAttribute($value) {
        $date = new Carbon();
        $date->setTimestamp($value);
        $this->attributes['join_begin'] = $date->toDateTimeString();
    }

    public function getJoinEndAttribute() {
        if (isset($this->attributes['join_end'])) {
            $date = new Carbon($this->attributes['join_end']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setJoinEndAttribute($value) {
        $date = new Carbon();
        $date->setTimestamp($value);
        $this->attributes['join_end'] = $date->toDateTimeString();
    }

    public function setRegionAttribute($value) {
        $addressId = $value['id'];
        $this->attributes['province_id'] = intval(substr($addressId, 0, 2).'0000');
        $this->attributes['province_name'] = $value['province'];
        $this->attributes['city_id'] = intval(substr($addressId, 0, 4).'00');
        $this->attributes['city_name'] = $value['city'];
        $this->attributes['county_id'] = intval(substr($addressId, 0, 6));
        $this->attributes['county_name'] = $value['district'];
    }

    public function getRegionAttribute() {
        if (!isset($this->attributes['county_id'])) {
            return null;
        }

        return [
            'id' => $this->attributes['county_id'],
            'province' => $this->attributes['province_name'],
            'city' => $this->attributes['city_name'],
            'district' => $this->attributes['county_name'],
        ];
    }

    public function setAddressAttribute($value) {
        $this->attributes['lng'] = $value['lng'];
        $this->attributes['lat'] = $value['lat'];
        $this->attributes['addr'] = $value['address'];
    }

    public function getAddressAttribute() {
        if (!isset($this->attributes['lng'])) {
            return null;
        }
        return [
            'lng' => $this->attributes['lng'],
            'lat' => $this->attributes['lat'],
            'address' => $this->attributes['addr'],
        ];
    }

    public function setTeamIdAttribute($value) {
        if (!empty($value)) {
            $parts = explode(",", $value);
            $value = array_pop($parts);
        }

        $this->attributes['team_id'] = $value;
    }

    public function team() {
        return $this->belongsTo('App\Models\Team', 'team_id', 'id');
    }

    public function org() {
        return $this->belongsTo('App\Models\Org', 'org_id', 'id');
    }


    public function syncServiceType() {
        if (!$this->id) {
            return false;
        }

        DB::table('project_service_category')->where('project_id', '=', $this->id)->delete();

        if ($this->project_type) {
            $inserts = [];

            foreach (explode(',', $this->project_type) as $item) {
                $inserts[] = [
                    'service_category_name' => $item,
                    'project_id' => $this->id,
                    'org_id'  => $this->org_id
                ];
            }

            DB::table('project_service_category')->insert($inserts);
        }
    }

    public function syncServiceTarget() {
        if (!$this->id) {
            return false;
        }

        DB::table('project_service_object')->where('project_id', '=', $this->id)->delete();

        if ($this->service_target) {
            $inserts = [];

            foreach (explode(',', $this->service_target) as $item) {
                $inserts[] = [
                    'service_object_name' => $item,
                    'project_id' => $this->id,
                    'org_id'  => $this->org_id
                ];
            }

            DB::table('project_service_object')->insert($inserts);
        }
    }

    public function plusTime($time) {
        return true;
        // 项目的时长是不会发生变化的。

//
//        if (!$this->id) {
//            return false;
//        }
//
//        $this->fill([
//            'reward_time' => $this->reward_time + $time
//        ]);
//
//        return $this->save();
    }
}
